#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     sync_helper
   文件功能描述 :   功能描述
   创建人 :       小钟同学
   创建时间 :          2021/7/19
-------------------------------------------------
   修改描述-2021/7/19:         
-------------------------------------------------
"""

from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
import typing as t


def run_sync(coroutine: t.Coroutine):
    """
    同步运行协程程序
    启动新的线程来完成想其他的协同程序的调用
    """
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        return asyncio.run(coroutine)
    else:
        if loop.is_running():
            new_loop = asyncio.new_event_loop()

            with ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(
                    new_loop.run_until_complete, coroutine
                )
                return future.result()
        else:
            return loop.run_until_complete(coroutine)